package org.cybzacg.encryption.monitoring.metrics;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

/**
 * 安全指标类
 * 收集和统计安全相关的指标数据
 * 
 * @author encryption team
 * @version 1.0
 */
public class SecurityMetrics {
    
    // 密钥管理统计
    private final AtomicLong keyGenerations = new AtomicLong(0);
    private final AtomicLong keyRotations = new AtomicLong(0);
    private final AtomicLong keyDestructions = new AtomicLong(0);
    private final AtomicLong keyImports = new AtomicLong(0);
    private final AtomicLong keyExports = new AtomicLong(0);
    
    // 安全事件统计
    private final AtomicLong securityViolations = new AtomicLong(0);
    private final AtomicLong authenticationFailures = new AtomicLong(0);
    private final AtomicLong authorizationFailures = new AtomicLong(0);
    private final AtomicLong encryptionFailures = new AtomicLong(0);
    private final AtomicLong decryptionFailures = new AtomicLong(0);
    private final AtomicLong signatureFailures = new AtomicLong(0);
    private final AtomicLong verificationFailures = new AtomicLong(0);
    
    // 异常操作统计
    private final AtomicLong suspiciousOperations = new AtomicLong(0);
    private final AtomicLong blockedOperations = new AtomicLong(0);
    private final AtomicLong auditEvents = new AtomicLong(0);
    
    // 算法使用统计
    private final Map<String, AlgorithmSecurityMetrics> algorithmMetrics = new ConcurrentHashMap<>();
    
    // 时间统计
    private volatile long lastKeyRotation = 0;
    private volatile long lastSecurityViolation = 0;
    private volatile long lastAuditEvent = 0;
    
    // 安全级别统计
    private final Map<String, AtomicLong> securityLevelUsage = new ConcurrentHashMap<>();
    
    /**
     * 记录密钥生成
     * 
     * @param algorithm 算法名称
     * @param keySize 密钥长度
     */
    public void recordKeyGeneration(String algorithm, int keySize) {
        keyGenerations.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordKeyGeneration(keySize);
    }
    
    /**
     * 记录密钥轮换
     * 
     * @param algorithm 算法名称
     * @param keySize 密钥长度
     */
    public void recordKeyRotation(String algorithm, int keySize) {
        keyRotations.incrementAndGet();
        lastKeyRotation = System.currentTimeMillis();
        getAlgorithmMetrics(algorithm).recordKeyRotation(keySize);
    }
    
    /**
     * 记录密钥销毁
     * 
     * @param algorithm 算法名称
     */
    public void recordKeyDestruction(String algorithm) {
        keyDestructions.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordKeyDestruction();
    }
    
    /**
     * 记录密钥导入
     * 
     * @param algorithm 算法名称
     */
    public void recordKeyImport(String algorithm) {
        keyImports.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordKeyImport();
    }
    
    /**
     * 记录密钥导出
     * 
     * @param algorithm 算法名称
     */
    public void recordKeyExport(String algorithm) {
        keyExports.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordKeyExport();
    }
    
    /**
     * 记录安全违规
     * 
     * @param violationType 违规类型
     * @param algorithm 算法名称
     */
    public void recordSecurityViolation(String violationType, String algorithm) {
        securityViolations.incrementAndGet();
        lastSecurityViolation = System.currentTimeMillis();
        getAlgorithmMetrics(algorithm).recordSecurityViolation(violationType);
    }
    
    /**
     * 记录认证失败
     * 
     * @param algorithm 算法名称
     */
    public void recordAuthenticationFailure(String algorithm) {
        authenticationFailures.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordAuthenticationFailure();
    }
    
    /**
     * 记录授权失败
     * 
     * @param algorithm 算法名称
     */
    public void recordAuthorizationFailure(String algorithm) {
        authorizationFailures.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordAuthorizationFailure();
    }
    
    /**
     * 记录加密失败
     * 
     * @param algorithm 算法名称
     */
    public void recordEncryptionFailure(String algorithm) {
        encryptionFailures.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordEncryptionFailure();
    }
    
    /**
     * 记录解密失败
     * 
     * @param algorithm 算法名称
     */
    public void recordDecryptionFailure(String algorithm) {
        decryptionFailures.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordDecryptionFailure();
    }
    
    /**
     * 记录签名失败
     * 
     * @param algorithm 算法名称
     */
    public void recordSignatureFailure(String algorithm) {
        signatureFailures.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordSignatureFailure();
    }
    
    /**
     * 记录验证失败
     * 
     * @param algorithm 算法名称
     */
    public void recordVerificationFailure(String algorithm) {
        verificationFailures.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordVerificationFailure();
    }
    
    /**
     * 记录可疑操作
     * 
     * @param operationType 操作类型
     * @param algorithm 算法名称
     */
    public void recordSuspiciousOperation(String operationType, String algorithm) {
        suspiciousOperations.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordSuspiciousOperation(operationType);
    }
    
    /**
     * 记录阻止操作
     * 
     * @param operationType 操作类型
     * @param algorithm 算法名称
     */
    public void recordBlockedOperation(String operationType, String algorithm) {
        blockedOperations.incrementAndGet();
        getAlgorithmMetrics(algorithm).recordBlockedOperation(operationType);
    }
    
    /**
     * 记录审计事件
     * 
     * @param eventType 事件类型
     * @param algorithm 算法名称
     */
    public void recordAuditEvent(String eventType, String algorithm) {
        auditEvents.incrementAndGet();
        lastAuditEvent = System.currentTimeMillis();
        getAlgorithmMetrics(algorithm).recordAuditEvent(eventType);
    }
    
    /**
     * 记录安全级别使用
     * 
     * @param securityLevel 安全级别
     */
    public void recordSecurityLevelUsage(String securityLevel) {
        securityLevelUsage.computeIfAbsent(securityLevel, k -> new AtomicLong(0)).incrementAndGet();
    }
    
    /**
     * 获取密钥生成数
     * 
     * @return 密钥生成数
     */
    public long getKeyGenerations() {
        return keyGenerations.get();
    }
    
    /**
     * 获取密钥轮换数
     * 
     * @return 密钥轮换数
     */
    public long getKeyRotations() {
        return keyRotations.get();
    }
    
    /**
     * 获取密钥销毁数
     * 
     * @return 密钥销毁数
     */
    public long getKeyDestructions() {
        return keyDestructions.get();
    }
    
    /**
     * 获取密钥导入数
     * 
     * @return 密钥导入数
     */
    public long getKeyImports() {
        return keyImports.get();
    }
    
    /**
     * 获取密钥导出数
     * 
     * @return 密钥导出数
     */
    public long getKeyExports() {
        return keyExports.get();
    }
    
    /**
     * 获取安全违规数
     * 
     * @return 安全违规数
     */
    public long getSecurityViolations() {
        return securityViolations.get();
    }
    
    /**
     * 获取认证失败数
     * 
     * @return 认证失败数
     */
    public long getAuthenticationFailures() {
        return authenticationFailures.get();
    }
    
    /**
     * 获取授权失败数
     * 
     * @return 授权失败数
     */
    public long getAuthorizationFailures() {
        return authorizationFailures.get();
    }
    
    /**
     * 获取加密失败数
     * 
     * @return 加密失败数
     */
    public long getEncryptionFailures() {
        return encryptionFailures.get();
    }
    
    /**
     * 获取解密失败数
     * 
     * @return 解密失败数
     */
    public long getDecryptionFailures() {
        return decryptionFailures.get();
    }
    
    /**
     * 获取签名失败数
     * 
     * @return 签名失败数
     */
    public long getSignatureFailures() {
        return signatureFailures.get();
    }
    
    /**
     * 获取验证失败数
     * 
     * @return 验证失败数
     */
    public long getVerificationFailures() {
        return verificationFailures.get();
    }
    
    /**
     * 获取可疑操作数
     * 
     * @return 可疑操作数
     */
    public long getSuspiciousOperations() {
        return suspiciousOperations.get();
    }
    
    /**
     * 获取阻止操作数
     * 
     * @return 阻止操作数
     */
    public long getBlockedOperations() {
        return blockedOperations.get();
    }
    
    /**
     * 获取审计事件数
     * 
     * @return 审计事件数
     */
    public long getAuditEvents() {
        return auditEvents.get();
    }
    
    /**
     * 获取最后密钥轮换时间
     * 
     * @return 最后密钥轮换时间戳
     */
    public long getLastKeyRotation() {
        return lastKeyRotation;
    }
    
    /**
     * 获取最后安全违规时间
     * 
     * @return 最后安全违规时间戳
     */
    public long getLastSecurityViolation() {
        return lastSecurityViolation;
    }
    
    /**
     * 获取最后审计事件时间
     * 
     * @return 最后审计事件时间戳
     */
    public long getLastAuditEvent() {
        return lastAuditEvent;
    }
    
    /**
     * 获取安全级别使用统计
     * 
     * @return 安全级别使用统计
     */
    public Map<String, Long> getSecurityLevelUsage() {
        Map<String, Long> result = new ConcurrentHashMap<>();
        securityLevelUsage.forEach((level, count) -> result.put(level, count.get()));
        return result;
    }
    
    /**
     * 获取算法安全指标
     * 
     * @param algorithm 算法名称
     * @return 算法安全指标
     */
    public AlgorithmSecurityMetrics getAlgorithmMetrics(String algorithm) {
        return algorithmMetrics.computeIfAbsent(algorithm, k -> new AlgorithmSecurityMetrics(algorithm));
    }
    
    /**
     * 获取所有算法安全指标
     * 
     * @return 算法安全指标映射
     */
    public Map<String, AlgorithmSecurityMetrics> getAllAlgorithmMetrics() {
        return new ConcurrentHashMap<>(algorithmMetrics);
    }
    
    /**
     * 获取总失败数
     * 
     * @return 总失败数
     */
    public long getTotalFailures() {
        return authenticationFailures.get() + authorizationFailures.get() +
               encryptionFailures.get() + decryptionFailures.get() +
               signatureFailures.get() + verificationFailures.get();
    }
    
    /**
     * 获取安全评分
     * 
     * @return 安全评分（0.0-100.0）
     */
    public double getSecurityScore() {
        long totalOperations = keyGenerations.get() + keyRotations.get() + 
                               keyImports.get() + keyExports.get();
        long totalFailures = getTotalFailures();
        
        if (totalOperations == 0) {
            return 100.0; // 没有操作，认为是安全的
        }
        
        double failureRate = (double) totalFailures / totalOperations;
        double violationRate = (double) securityViolations.get() / Math.max(totalOperations, 1);
        
        // 基础分数100分，失败率扣分，违规率扣分
        double score = 100.0 - (failureRate * 50.0) - (violationRate * 30.0);
        return Math.max(0.0, Math.min(100.0, score));
    }
    
    /**
     * 重置所有指标
     */
    public void reset() {
        keyGenerations.set(0);
        keyRotations.set(0);
        keyDestructions.set(0);
        keyImports.set(0);
        keyExports.set(0);
        
        securityViolations.set(0);
        authenticationFailures.set(0);
        authorizationFailures.set(0);
        encryptionFailures.set(0);
        decryptionFailures.set(0);
        signatureFailures.set(0);
        verificationFailures.set(0);
        
        suspiciousOperations.set(0);
        blockedOperations.set(0);
        auditEvents.set(0);
        
        lastKeyRotation = 0;
        lastSecurityViolation = 0;
        lastAuditEvent = 0;
        
        algorithmMetrics.clear();
        securityLevelUsage.clear();
    }
    
    @Override
    public String toString() {
        return String.format(
            "SecurityMetrics:\n" +
            "  Key Management: Gen=%d, Rot=%d, Dest=%d, Imp=%d, Exp=%d\n" +
            "  Security Events: Violations=%d, AuthFail=%d, AuthzFail=%d\n" +
            "  Crypto Failures: Enc=%d, Dec=%d, Sig=%d, Ver=%d\n" +
            "  Suspicious: SuspOps=%d, BlockedOps=%d, Audit=%d\n" +
            "  Security Score: %.1f/100.0\n" +
            "  Last Events: KeyRot=%d, Violation=%d, Audit=%d",
            getKeyGenerations(), getKeyRotations(), getKeyDestructions(), 
            getKeyImports(), getKeyExports(),
            getSecurityViolations(), getAuthenticationFailures(), getAuthorizationFailures(),
            getEncryptionFailures(), getDecryptionFailures(), 
            getSignatureFailures(), getVerificationFailures(),
            getSuspiciousOperations(), getBlockedOperations(), getAuditEvents(),
            getSecurityScore(),
            getLastKeyRotation(), getLastSecurityViolation(), getLastAuditEvent()
        );
    }
    
    /**
     * 算法安全指标类
     */
    public static class AlgorithmSecurityMetrics {
        
        private final String algorithm;
        
        // 密钥操作统计
        private final AtomicLong keyGenerations = new AtomicLong(0);
        private final AtomicLong keyRotations = new AtomicLong(0);
        private final AtomicLong keyDestructions = new AtomicLong(0);
        private final AtomicLong keyImports = new AtomicLong(0);
        private final AtomicLong keyExports = new AtomicLong(0);
        
        // 安全事件统计
        private final AtomicLong securityViolations = new AtomicLong(0);
        private final AtomicLong authenticationFailures = new AtomicLong(0);
        private final AtomicLong authorizationFailures = new AtomicLong(0);
        private final AtomicLong encryptionFailures = new AtomicLong(0);
        private final AtomicLong decryptionFailures = new AtomicLong(0);
        private final AtomicLong signatureFailures = new AtomicLong(0);
        private final AtomicLong verificationFailures = new AtomicLong(0);
        
        // 异常操作统计
        private final AtomicLong suspiciousOperations = new AtomicLong(0);
        private final AtomicLong blockedOperations = new AtomicLong(0);
        private final AtomicLong auditEvents = new AtomicLong(0);
        
        // 密钥长度统计
        private volatile int minKeySize = Integer.MAX_VALUE;
        private volatile int maxKeySize = 0;
        private volatile long totalKeySize = 0;
        private volatile long keyCount = 0;
        
        /**
         * 构造函数
         * 
         * @param algorithm 算法名称
         */
        public AlgorithmSecurityMetrics(String algorithm) {
            this.algorithm = algorithm;
        }
        
        /**
         * 记录密钥生成
         */
        public void recordKeyGeneration(int keySize) {
            keyGenerations.incrementAndGet();
            updateKeySizeStats(keySize);
        }
        
        /**
         * 记录密钥轮换
         */
        public void recordKeyRotation(int keySize) {
            keyRotations.incrementAndGet();
            updateKeySizeStats(keySize);
        }
        
        /**
         * 记录密钥销毁
         */
        public void recordKeyDestruction() {
            keyDestructions.incrementAndGet();
        }
        
        /**
         * 记录密钥导入
         */
        public void recordKeyImport() {
            keyImports.incrementAndGet();
        }
        
        /**
         * 记录密钥导出
         */
        public void recordKeyExport() {
            keyExports.incrementAndGet();
        }
        
        /**
         * 记录安全违规
         */
        public void recordSecurityViolation(String violationType) {
            securityViolations.incrementAndGet();
        }
        
        /**
         * 记录认证失败
         */
        public void recordAuthenticationFailure() {
            authenticationFailures.incrementAndGet();
        }
        
        /**
         * 记录授权失败
         */
        public void recordAuthorizationFailure() {
            authorizationFailures.incrementAndGet();
        }
        
        /**
         * 记录加密失败
         */
        public void recordEncryptionFailure() {
            encryptionFailures.incrementAndGet();
        }
        
        /**
         * 记录解密失败
         */
        public void recordDecryptionFailure() {
            decryptionFailures.incrementAndGet();
        }
        
        /**
         * 记录签名失败
         */
        public void recordSignatureFailure() {
            signatureFailures.incrementAndGet();
        }
        
        /**
         * 记录验证失败
         */
        public void recordVerificationFailure() {
            verificationFailures.incrementAndGet();
        }
        
        /**
         * 记录可疑操作
         */
        public void recordSuspiciousOperation(String operationType) {
            suspiciousOperations.incrementAndGet();
        }
        
        /**
         * 记录阻止操作
         */
        public void recordBlockedOperation(String operationType) {
            blockedOperations.incrementAndGet();
        }
        
        /**
         * 记录审计事件
         */
        public void recordAuditEvent(String eventType) {
            auditEvents.incrementAndGet();
        }
        
        /**
         * 更新密钥长度统计
         */
        private void updateKeySizeStats(int keySize) {
            if (keySize < minKeySize) {
                minKeySize = keySize;
            }
            if (keySize > maxKeySize) {
                maxKeySize = keySize;
            }
            totalKeySize += keySize;
            keyCount++;
        }
        
        /**
         * 获取算法名称
         * 
         * @return 算法名称
         */
        public String getAlgorithm() {
            return algorithm;
        }
        
        /**
         * 获取最小密钥长度
         * 
         * @return 最小密钥长度
         */
        public int getMinKeySize() {
            return minKeySize == Integer.MAX_VALUE ? 0 : minKeySize;
        }
        
        /**
         * 获取最大密钥长度
         * 
         * @return 最大密钥长度
         */
        public int getMaxKeySize() {
            return maxKeySize;
        }
        
        /**
         * 获取平均密钥长度
         * 
         * @return 平均密钥长度
         */
        public double getAverageKeySize() {
            return keyCount > 0 ? (double) totalKeySize / keyCount : 0.0;
        }
        
        /**
         * 获取总密钥操作数
         * 
         * @return 总密钥操作数
         */
        public long getTotalKeyOperations() {
            return keyGenerations.get() + keyRotations.get() + keyDestructions.get() +
                   keyImports.get() + keyExports.get();
        }
        
        /**
         * 获取总安全事件数
         * 
         * @return 总安全事件数
         */
        public long getTotalSecurityEvents() {
            return securityViolations.get() + authenticationFailures.get() + 
                   authorizationFailures.get() + encryptionFailures.get() + 
                   decryptionFailures.get() + signatureFailures.get() + 
                   verificationFailures.get();
        }
        
        @Override
        public String toString() {
            return String.format(
                "AlgorithmSecurityMetrics[%s]:\n" +
                "  Key Ops: Gen=%d, Rot=%d, Dest=%d, Imp=%d, Exp=%d\n" +
                "  Key Sizes: Min=%d, Max=%d, Avg=%.1f\n" +
                "  Security Events: Total=%d, Violations=%d\n" +
                "  Failures: Auth=%d, Authz=%d, Enc=%d, Dec=%d, Sig=%d, Ver=%d\n" +
                "  Suspicious: SuspOps=%d, BlockedOps=%d, Audit=%d",
                algorithm, keyGenerations.get(), keyRotations.get(), keyDestructions.get(),
                keyImports.get(), keyExports.get(), getMinKeySize(), getMaxKeySize(),
                getAverageKeySize(), getTotalSecurityEvents(), securityViolations.get(),
                authenticationFailures.get(), authorizationFailures.get(), encryptionFailures.get(),
                decryptionFailures.get(), signatureFailures.get(), verificationFailures.get(),
                suspiciousOperations.get(), blockedOperations.get(), auditEvents.get()
            );
        }
    }
}
